package com.hbu.product.hbumallproduct.exception;

import com.hbu.common.exception.BizCodeEnum;
import com.hbu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: hbu-mall
 * @Package: com.hbu.product.hbumallproduct.exception
 * @ClassName: ExceptionControllerAdvice
 * @Author: zxh
 * @Description:
 * @Date: 2022/11/11 19:19
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.hbu.product.hbumallproduct.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> resultMap = new HashMap<>(8);
        bindingResult.getFieldErrors().forEach(iter -> {
            resultMap.put(iter.getField(), iter.getDefaultMessage());
        });
        log.error("参数校验异常", e);
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", resultMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleAllException(Throwable e) {
        log.error("系统异常", e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
